package com.twetec.cms.adapter.pc.backend.controller.website;

import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.common.constant.FileConst;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.vo.website.ImageFileNameVO;
import com.twetec.cms.service.file.FastdfsFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(tags = "富文本控制器")
@RestController
@RequestMapping("/website/rich-text")
public class RichTextController {

    @Autowired
    private FastdfsFileService fastdfsFileService;

    @ApiOperation(value = "图片上传", notes = "图片上传")
    @PostMapping("/upload-image")
    public R<ImageFileNameVO> uploadImage(
            @ApiParam(value = "file", required = true, example = "1.png") @RequestParam(required = false) MultipartFile file) throws IOException {

        // 校验上传文件是否为空
        if(null == file) return R.failureRequestParam().msg("上传图片文件参数为空");

        // file.getOriginalFilename()得到上传时的文件名(仅返回文件名,并不会包含路径) 并校验是否是图片
        if(!ValidateUtil.isPicture(file.getOriginalFilename())) return R.failureRequestParam().msg("该文件不是图片");

        // file.getSize()以字节为单位返回指定文件的大小   <2M
        if(file.getSize() > FileConst.UPLOAD_LOGO_PICTURE_SIZE) return R.failureRequestParam().msg("图片大小不能超过"+FileConst.UPLOAD_LOGO_PICTURE_SIZE+"M");

        // 进行上传操作
        String fileUrl = fastdfsFileService.uploadImage(file);

        // 返回文件路径
        ImageFileNameVO imageFileNameVO = new ImageFileNameVO();
        imageFileNameVO.setFileUrl(fileUrl);
        return R.success().data(imageFileNameVO);
    }

}
